package com.app.shop.controller.system;

import com.app.shop.util.ApiRest;
import com.app.shop.entity.SysMenu;
import com.app.shop.entity.SysReAuthMenu;
import com.app.shop.entity.SysReAuthUser;
import com.app.shop.entity.query.SysMenuQuery;
import com.app.shop.config.security.DgbSecurityUserHelper;
import com.app.shop.config.security.ValidateCodeHandle;
import com.app.shop.service.system.SysAuthService;
import com.app.shop.service.system.SysMenuService;
import com.app.shop.service.system.SysReAuthMenuService;
import com.app.shop.service.system.SysReAuthUserService;
import com.app.shop.util.VerificationCode;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 系统默认初始化服务
 *
 * @author chen li wei
 * @version 21:14 2019-5-10
 */
@Controller
@RequestMapping(value = "/system")
public class SystemController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    SysAuthService sysAuthService;
    @Autowired
    SysReAuthMenuService sysReAuthMenuService;
    @Autowired
    SysReAuthUserService sysReAuthUserService;

    /**
     * 登录随机数字字母组合验证码
     *
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     * @throws Exception IO读写异常
     * @author chenliwei
     */
    @RequestMapping(value = "/verificationCode", method = RequestMethod.GET)
    public void verificationCode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        //获取验证码
        String code = VerificationCode.drawImg(output);
        ServletOutputStream out = response.getOutputStream();
        ValidateCodeHandle.save(session.getId(), code);
        //输出验证码
        output.writeTo(out);
    }


    /**
     * 用户退出系统方法
     *
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     * @return 返回登录主页（login.html）
     * @author chenliwei
     */
    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    public ModelAndView loginOut(HttpServletResponse response, HttpServletRequest request) {
        //获取Security用户权限对象
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        //如果权限存在进行退出
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("login");
        return mv;
    }


    /**
     * 用户登录后获取用户菜单
     *
     * @return 返回当前用户菜单
     */
    @ResponseBody
    @RequestMapping(value = "/loginInfo", method = RequestMethod.POST)
    public ApiRest LoginInfo() {
        ApiRest apiRest = new ApiRest();
        //获取用户Id
        Integer userId = DgbSecurityUserHelper.getUserInfo().getUserId();
        //根据用户Id查询权限信息
        List<SysReAuthUser> sysReAuthUserList = sysReAuthUserService.getSysAuthListByUserId(userId);
        //循环获取所有有效菜单
        List<SysMenu> sysMenuResList = new ArrayList<SysMenu>();
        if (sysReAuthUserList.size() > 0) {
            List<Integer> authIds = new ArrayList<Integer>();
            for (SysReAuthUser sysReAuthUser : sysReAuthUserList) {
                authIds.add(sysReAuthUser.getAuthId());
            }
            //根据用户查询权限对应菜单
            List<SysReAuthMenu> sysReAuthMenuList = sysReAuthMenuService.getSysMenuListByAuthId(authIds);

            //根据用户权限菜单进行循环
            Set<Integer> set = new HashSet<Integer>();
            for (SysReAuthMenu sysReAuthMenu : sysReAuthMenuList) {
                set.add(sysReAuthMenu.getMenuId());
            }
            //查询所有菜单列表
            List<SysMenu> sysMenuList = sysMenuService.getSysMenuList(new SysMenuQuery());
            //
            if (sysMenuList != null) {
                for (SysMenu sysMenu : sysMenuList) {
                    if (set.contains(sysMenu.getMenuId())) {
                        set.add(sysMenu.getParentId());
                    }
                }
                for (SysMenu sysMenu : sysMenuList) {
                    if (set.contains(sysMenu.getMenuId())) {
                        sysMenuResList.add(sysMenu);
                    }
                }
            }
            log.debug(JSONObject.toJSON(sysMenuResList).toString());
        }
        JSONObject jsonObject = new JSONObject();
        //用户姓名，账号，最后一次登录时间，最后一次登录IP
        jsonObject.put("userInfo", "");
        //菜单信息
        jsonObject.put("menuInfo", sysMenuResList);

        apiRest.setCode(200);
        apiRest.setData(jsonObject);
        return apiRest;
    }

}
